package me.shiqiang.im.consumer;

import com.aliyun.openservices.ons.api.Action;
import com.aliyun.openservices.ons.api.ConsumeContext;
import com.aliyun.openservices.ons.api.Message;
import com.corundumstudio.socketio.SocketIOClient;
import me.shiqiang.im.common.ConnectionServer;
import me.shiqiang.im.common.SocketClientMap;
import me.shiqiang.im.enums.MessageCType;
import me.shiqiang.im.msg.DistributeMsgBody;
import me.shiqiang.im.service.MsgService;
import me.shiqiang.im.utils.JsonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.Set;

/**
 * @author cuishiqiang
 * @date 2017/12/16 下午3:56
 */
@Component(MessageCType.GROUP)
public class GroupMsgListener implements MsgListener{
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    MsgService service;


    @Override
    public Action consume(Message message, ConsumeContext context) {
        String msgBodyStr = new String(message.getBody());
        try {
            logger.info("群收到消息: {}", msgBodyStr);
            DistributeMsgBody msgBody = JsonUtils.getInstance().fromJson(msgBodyStr, DistributeMsgBody.class);
            Long groupId = Long.parseLong(message.getUserProperties("to"));
            Long syncKey = Long.parseLong(message.getUserProperties("syncKey"));
            Map<String, ConnectionServer> connectionServerMap = SocketClientMap.getInstance().connectionServerMap;
            logger.info("q的connectionServerMap的size{}", connectionServerMap.size());
            Set<String> serverIdSet = service.getGroupServerIdSet(String.valueOf(groupId));
            for (String serverId : serverIdSet) {
                ConnectionServer connectionServer = connectionServerMap.get(serverId);
                if (connectionServer == null || connectionServer.businessProcessors.isEmpty()) {
                    logger.info("serverId{},business未连接", serverId);
                    continue;
                }
                SocketIOClient processor = connectionServer.nextProcessor();

                processor.sendEvent("groupMsg",msgBody);
                logger.info("群消息发送:serverId{},machineId{}",processor.get("serverId"),processor.get("machineId"));
            }


            return Action.CommitMessage;
        } catch (Exception e) {
            logger.error(String.format("消息处理失败：%s", msgBodyStr), e);
            return Action.ReconsumeLater;
        }
    }
}
